package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.DeviceType;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.MySocket;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.util.ConvertUtil;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.tiqiaa.client.IRemoteClient;
import com.tiqiaa.client.IRemoteClient.CallBackOnRemoteDownloaded;
import com.tiqiaa.client.IRemoteClient.CallbackOnMatchDone;
import com.tiqiaa.client.impl.RemoteClient;
import com.tiqiaa.constant.ApplianceType;
import com.tiqiaa.icontrol.util.LanguageUtils;
import com.tiqiaa.ircode.impl.InfraredFetcher;
import com.tiqiaa.irdnasdk.IrDnaSdkHelper;
import com.tiqiaa.remote.entity.Infrared;
import com.tiqiaa.remote.entity.Key;
import com.tiqiaa.remote.entity.MatchPage;
import com.tiqiaa.remote.entity.MatchPage.IRMark;
import com.tiqiaa.remote.entity.Page;
import com.tiqiaa.remote.entity.Remote;
import com.umeng.socialize.utils.Log;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AddFanActivity1 extends BaseActivity implements CallbackOnMatchDone ,IRemoteClient.CallbackOnSearchDone ,IRemoteClient.CallbackOnAutoMatchDone{
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private Button mPowerB;
	private TextView mTitleTv;
	private Button mWindB;
	private Button mSpeedB;
	private Button mTimeB;
	private Button mShakeB;
	// private Button mPreB;
	// private Button mNextB;
	private Button cancel_btn;
	private Button ensure_btn;
	private MySocket socket;
	private Vibrator vibrator;
	private SVProgressHUD mSVProgressHUD;
	private Dialog dialog;
	protected String selected_remote_id;
	private int type;
	private String aplliance = "风扇";
	private String brand;
	private long brandId;
	// private Remote remote;
	private List<Key> keys;
	private int currentMatchIndex = 0;// 当前匹配的是第一个遥控器
	private Remote currentRemote;
	private List<Remote> matchRemotes = new ArrayList<Remote>(); // 当前匹配按键的所有遥控器，与按键有关
	private List<IRMark> failedmarks = new ArrayList<IRMark>();
	private MatchPage matchPage = new MatchPage();
	// 精确匹配信号特征集合
	private List<IRMark> marks = new ArrayList<IRMark>();
	private List<Integer> failedKeys = new ArrayList<Integer>(); // 未匹配成功的按键，一个按键在所有的遥控器数据都匹配完后还没有匹配到，此时需要将它标记
	private List<Button> buttons = new ArrayList<Button>();
	private HashMap<Integer, String> irDataMaps = new HashMap<Integer, String>();
    private Page page = new Page();;

    @Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;
		case R.id.power_b:
			sendPowerCmd();
			vibrator.vibrate(50);
			break;
		case R.id.wind_btn:
			// 838
			sendCmd();
			vibrator.vibrate(50);
			break;
		case R.id.time_btn:
			// 876
			sendCmd();
			vibrator.vibrate(50);
			break;
		case R.id.shake_btn:
			// 836
			sendCmd();
			vibrator.vibrate(50);
			break;
		case R.id.speed_btn:
			// 838
			sendCmd();
			vibrator.vibrate(50);
			break;
		case R.id.cancel_btn:
			dialog.dismiss();
			IRMark failedMarked = new IRMark();
			failedMarked.setIr_mark(currentRemote.getKeys().get(0).getInfrareds().get(0).getIr_mark());
			failedMarked.setKey_type(currentRemote.getKeys().get(0).getInfrareds().get(0).getKey_type());
			failedmarks.add(failedMarked);
			if (currentMatchIndex < matchRemotes.size() - 1) {
				currentMatchIndex++;
				currentRemote = matchRemotes.get(currentMatchIndex);
				mTitleTv.setText(
						"匹配" + brand + " 风扇" + "(" + (currentMatchIndex + 1) + "/" + matchRemotes.size() + ")");
				refreshKey();
			} else {
				// 获取此按键的更多遥控器信号
				match();
			}

			break;
		case R.id.ensure_btn:
			dialog.dismiss();
			Log.i("wmy", "matchRemotes.size() = " + matchRemotes.size() + " currentMatchIndex = " + currentMatchIndex);
			selected_remote_id = currentRemote.getId();
			// 精确匹配信号特征
			IRMark okMarked = new IRMark();
			// 该特征的标签为遥控器第一个按键的红外码的标签
			okMarked.setIr_mark(currentRemote.getKeys().get(0).getInfrareds().get(0).getIr_mark());
			// 该特征的按键类型为遥控器第一个按键的红外码的按键类型
			okMarked.setKey_type(currentRemote.getKeys().get(0).getInfrareds().get(0).getKey_type());
			// 将该特征添加至特征的集合中
			marks.add(okMarked);
			// 将失败的特征码清除
			failedmarks.clear();
			// 将当前已匹配的所有遥控器的集合清除 以便获取新案件的匹配遥控器时不重复添加
			matchRemotes.clear();
			// 当前所选遥控器的位置为0
			currentMatchIndex = 0;
			// 重新获取新按键的匹配遥控器
			mSVProgressHUD.showWithStatus("正在加载");
			match();

			break;

		default:
			break;
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_fan1;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mTitleTv = $(R.id.title_tv);
		mPowerB = $(R.id.power_b);
		mTimeB = $(R.id.time_btn);
		mWindB = $(R.id.wind_btn);
		mShakeB = $(R.id.shake_btn);
		mSpeedB = $(R.id.speed_btn);
		buttons.add(mTimeB);
		buttons.add(mWindB);
		buttons.add(mShakeB);
		buttons.add(mSpeedB);
		buttons.add(mPowerB);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		type = getIntent().getIntExtra("type", 999);
		brand = getIntent().getStringExtra("brand");
		brandId = getIntent().getLongExtra("brandId", 999);
		socket = SocketManager.getInstance().sMap.get(DeviceManager.getInstance().getmWlanId());
		if (socket == null) {
			ToastShow.Show(getApplicationContext(), "请重新选择网关再添加！");
			// return;
			finish();
		}
		mSVProgressHUD = new SVProgressHUD(AddFanActivity1.this);
		boolVersion();
		mBackL.setOnClickListener(this);
		mTimeB.setOnClickListener(this);
		mWindB.setOnClickListener(this);
		mShakeB.setOnClickListener(this);
		mPowerB.setOnClickListener(this);
		mSpeedB.setOnClickListener(this);
		setListeners();

	}

	private void setListeners() {
		failedmarks.clear();
		matchRemotes.clear();
		currentMatchIndex = 0;
		mSVProgressHUD.showWithStatus("正在加载");
		match();
	}



	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

	private void showConfirmDialog() {
		dialog = new Dialog(AddFanActivity1.this);
		dialog.setContentView(R.layout.dialog_confirm_respond);
		TextView remind_tv = (TextView) dialog.findViewById(R.id.remind_tv);
		remind_tv.setText("请观察风扇是否有正确响应");
		cancel_btn = (Button) dialog.findViewById(R.id.cancel_btn);
		ensure_btn = (Button) dialog.findViewById(R.id.ensure_btn);
		cancel_btn.setOnClickListener(this);
		ensure_btn.setOnClickListener(this);
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

	protected void match() {
		IRemoteClient client = new RemoteClient(getApplicationContext());
		Log.i("wmy", "type = " + type + " brandId = " + brandId);
		matchPage.setAppliance_type(ApplianceType.FAN);
		matchPage.setBrand_id(brandId);

		matchPage.setOkMarks(marks);
		matchPage.setWrongMarks(failedmarks);
		matchPage.setFailedKeys(failedKeys);
		client.exactMatchReomtes(matchPage, true, AddFanActivity1.this);

		//搜索匹配
         RemoteClient client1=new RemoteClient(getApplicationContext());
		// 刷新当前匹配条件展示
        // 电器类型可以指定，也可以是0（全部，默认）
        page.setAppliance_type(ApplianceType.FAN);
        // 品牌ID可以指定，也可以用Brand.BRAND_ID_ALL（默认）或Brand.BRAND_ID_OTHER
        page.setBrand_id(brandId); // 康佳
        // 关键词可以指定，也可以为空或null（默认）
        page.setKeyword("美的");
        // App当前使用的语言
        page.setLang(LanguageUtils.getLang());
      //  client1.searchOfficial(this.page,  this);
		//自动匹配
		//client1.autoMatchRemotes(this.page, this);
    }




	@Override
	public void onMatchDone(int errcode, List<Remote> remotes) {
		// TODO Auto-generated method stub
		if (mSVProgressHUD.isShowing()) {
			mSVProgressHUD.dismiss();
		}
		// footerBtn.setVisibility(View.GONE);
		if (errcode == CallbackOnMatchDone.ERROR_CODE_SUCCESS) {
			if (remotes != null && remotes.size() > 0) {
				matchRemotes.addAll(remotes);
				currentRemote = matchRemotes.get(0);
				refreshMatchView();
			} else {
				// showToast("无更多遥控器,忽略此按键");
				failedKeys.add(matchPage.getNext_key());
				// 此按键匹配失败，忽略此按键，匹配下一个按键，
				failedmarks.clear();
				matchRemotes.clear();
				currentMatchIndex = 0;
				match();
			}
		} else if (errcode == CallbackOnMatchDone.ERROR_MATCH_COMPLETED && selected_remote_id != null) {
			showSuccessDialog();
		} else {
			showToast("匹配失败");
			Intent intent = new Intent(AddFanActivity1.this, ModelSelectionActivity1.class);
			intent.putExtra("type", DeviceType.DEVICE_TYPE_FAN);
			intent.putExtra("brand", brand);
			intent.putExtra("brandId", brandId);
			startActivity(intent);
			finish();
		}
	}

	@Override
	public void onAutoMatchDone(int errcode, List<Remote> remoteList) {
		if (remoteList != null && remoteList.size() > 0) {

		} else {

		}
	}

	@Override
	public void onSearchDone(int errcode, List<Remote> remoteList) {
		if (remoteList != null && remoteList.size() > 0) {
			//  showRemoteList(remoteList);
		} else {
			// onNoRemote();
		}
	}


	private void refreshMatchView() {
		mTitleTv.setText("匹配" + brand + " 风扇" + "(" + (currentMatchIndex + 1) + "/" + matchRemotes.size() + ")");
		if (currentMatchIndex == 0) {
			refreshKey();
		}
	}

	private void showSuccessDialog() {
		// showToast("匹配完成！匹配到的遥控器ID为：" + selected_remote_id);
		mSVProgressHUD.showWithStatus("正在保存");
		IRemoteClient client = new RemoteClient(getApplicationContext());
		client.download_reomte(selected_remote_id, new CallBackOnRemoteDownloaded() {
			@Override
			public void onRemoteDownloaded(int errcode, final Remote remote1) {
				if (errcode != CallBackOnRemoteDownloaded.ERROR_CODE_SUCCESS) {
					if (mSVProgressHUD.isShowing()) {
						mSVProgressHUD.dismiss();
					}
					showToast("下载遥控器失败,请重试");
					finish();
				} else {
					currentRemote = remote1;
					boolean e = DeviceManager.getInstance()
							.checkName(aplliance + " " + brand + " " + currentRemote.getModel());
					if (e) {
						ToastShow.Show(getApplicationContext(),
								"匹配成功，遥控器：" + aplliance + " " + brand + " " + currentRemote.getModel() + "已存在,无需添加");
						finish();
					} else {
						save();
					}
				}
			}
		});
	}

	// 刷新当前匹配的按键
	private void refreshKey() {
		Log.i("wmy", "refreshKey 当前按键的type = " + matchRemotes.get(currentMatchIndex).getKeys().get(0).getType());
		Log.i("wmy", "refreshKey 当前按键的IR特征 = "
				+ matchRemotes.get(currentMatchIndex).getKeys().get(0).getInfrareds().get(0).getIr_mark());
		switch (matchRemotes.get(currentMatchIndex).getKeys().get(0).getType()) {
		case 800:
			resetBg();
			mPowerB.setClickable(true);
			mPowerB.setBackgroundResource(R.drawable.kaiguan12x);
			break;
		case 836:
			resetBg();
			mShakeB.setClickable(true);
			mShakeB.setBackgroundResource(R.drawable.selector_shake);
			break;
		case 837:
			resetBg();
			mWindB.setClickable(true);
			mWindB.setBackgroundResource(R.drawable.selector_wind_class);
			break;
		case 838:
			resetBg();
			mSpeedB.setClickable(true);
			mSpeedB.setBackgroundResource(R.drawable.selector_wind_speed);
			break;
		default:
			break;
		}
	}

	private void resetBg() {
		for (int i = 0; i < buttons.size(); i++) {
			buttons.get(i).setClickable(false);
		}
		mPowerB.setBackgroundResource(R.drawable.kaiguan32x);
		mTimeB.setBackgroundResource(R.drawable.kuang2x);
		mWindB.setBackgroundResource(R.drawable.kuang2x);
		mSpeedB.setBackgroundResource(R.drawable.kuang2x);
		mShakeB.setBackgroundResource(R.drawable.kuang2x);
	}

	private void sendCmd() {
		byte[] data = IrDnaSdkHelper.getIrCode(
				matchRemotes.get(currentMatchIndex).getKeys().get(0).getInfrareds().get(0).getFreq(),
				matchRemotes.get(currentMatchIndex).getKeys().get(0).getInfrareds().get(0).getData());
		String str = bytesToHexString(data).toUpperCase();
		String cmd = ConvertUtil.getInstance().convertInfraredCmd(str);
		if (socket.isLocalSuccess()) {
			socket.sendMqttData(cmd);
		} else {
			SocketManager.getInstance().sendRemoteData(socket.getMac(), DeviceManager.getInstance().getmWlanId(), cmd);
		}
		showConfirmDialog();
	}

	private void sendPowerCmd() {
		int pos = 0;
		for (int i = 0; i < matchRemotes.get(currentMatchIndex).getKeys().size(); i++) {
			if (matchRemotes.get(currentMatchIndex).getKeys().get(i).getType() == 800) {
				pos = i;
				break;
			}
		}
		byte[] data = IrDnaSdkHelper.getIrCode(
				matchRemotes.get(currentMatchIndex).getKeys().get(pos).getInfrareds().get(0).getFreq(),
				matchRemotes.get(currentMatchIndex).getKeys().get(pos).getInfrareds().get(0).getData());
		String str = bytesToHexString(data).toUpperCase();
		String cmd = ConvertUtil.getInstance().convertInfraredCmd(str);
		if (socket.isLocalSuccess()) {
			socket.sendMqttData(cmd);
		} else {
			SocketManager.getInstance().sendRemoteData(socket.getMac(), DeviceManager.getInstance().getmWlanId(), cmd);
		}
		showConfirmDialog();
	}

	// 保存该遥控器
	private void save() {
		if (currentRemote == null) {
			Log.i("wmy", "remote 为空");
			ToastShow.Show(getApplicationContext(), "添加失败，没有该遥控器");
			finish();
			return;
		} else {

		}
		keys = currentRemote.getKeys();
		// 上传设备
		RequestParams params = new RequestParams(HttpURL.UPLOAD_DEVICE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("classification", "4");
			obj.put("key", "10000");
			obj.put("deviceModel", currentRemote.getId());
			obj.put("deviceName", aplliance + " " + brand + " " + currentRemote.getModel());
			obj.put("deviceType", type + "");
			obj.put("deviceVersion", "3.1.0");
			obj.put("deviceWifiSSID", currentRemote.getId().equals("") ? "未知" : currentRemote.getId());
			obj.put("deviceId", "0");
			obj.put("productId", "4");
			obj.put("mainDeviceId", DeviceManager.getInstance().getmWlanId());
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.e("wmy", " upload remote = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "upload remote result=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						String deviceId = jsonObject.getString("data");
						// 获取deviceId之后 上传所有按键
						uploadKeys(deviceId);
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void uploadKeys(String deviceId) {
		// 上传按键
		initKey();
		String buttonCmdS = "";
		String positionS = "";
		String nameS = "";
		for (int i = 0; i < keys.size(); i++) {
			buttonCmdS += irDataMaps.get(keys.get(i).getType()) + ",";
			positionS += keys.get(i).getType() + ",";
			nameS += keys.get(i).getLocalName() + ",";
		}
		if (buttonCmdS.length() > 1) {
			buttonCmdS = buttonCmdS.substring(0, buttonCmdS.length() - 1);
		}
		if (positionS.length() > 1) {
			positionS = positionS.substring(0, positionS.length() - 1);
		}
		if (nameS.length() > 1) {
			nameS = nameS.substring(0, nameS.length() - 1);
		}
		RequestParams params = new RequestParams(HttpURL.UPLOAD_REMOTE_KEY_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("buttonCmdS", buttonCmdS);
			obj.put("key", "10000");
			obj.put("positionS", positionS);
			obj.put("deviceId", deviceId);
			obj.put("nameS", nameS);
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			Log.e("wmy", " upload remote keys = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "upload remote keys result=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);
					String value = jsonObject.getString("resultCode");
					if (value.equals("1")) {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "保存成功");
						finish();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						String errorMsg = jsonObject.getString("errorMsg");
						ToastShow.Show(getApplicationContext(), "保存失败：" + errorMsg);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

		});
	}

	private void initKey() {
		keys = currentRemote.getKeys();
		for (int i = 0; i < keys.size(); i++) {
			List<Infrared> infrareds = null;
			infrareds = new InfraredFetcher(this).fetchInfrareds(currentRemote, keys.get(i));
			if (infrareds != null) {
				for (Infrared ir : infrareds) {
					if (ir != null && ir.getData() != null) {
						// int freq = ir.getFreq();
						// Required ！ 必须调用，此接口将对信号格式进行验证，返回明码信号数据
						// Log.i("wmy", "ir.getData() = "+ir.getData());
						byte[] data = IrDnaSdkHelper.getIrCode(ir.getFreq(), ir.getData());
						// byte[] airData =
						// IrDnaSdkHelper.getAirVMCode(keys.get(i).getProtocol());
						// data格式详见《信号数据格式说明》文档，不同的芯片需要转换成对应的芯片目标码
						// String str = byte2HexStr(data);
						String str = bytesToHexString(data).toUpperCase();
						String cmd = ConvertUtil.getInstance().convertInfraredCmd(str);
						// Log.w("wmy",
						// "send....###..解析出的红外数据..data = "+cmd+" " +
						// Arrays.toString(data));
						// Log.e("wmy", keys.get(i).getType() + " " + cmd);
						irDataMaps.put(keys.get(i).getType(), str);
					}
				}
			}
		}
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

}
